package cn.jhz.learn.blog.service.core.open.file.impl;

import cn.jhz.learn.blog.dao.file.BlogFileMapper;
import cn.jhz.learn.blog.po.file.BlogFileContent;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.jhz.learn.blog.service.core.open.file.FileService;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;

import java.io.IOException;
import java.io.OutputStream;
import java.util.List;


@Service("fileService")
public class FileServiceImpl implements FileService {

	private final BlogFileMapper fileMapper;

	@Autowired
	public FileServiceImpl(BlogFileMapper fileMapper) {
		this.fileMapper = fileMapper;
	}

	@Override
	public StreamingResponseBody download(String signatureCodes) {
		List<BlogFileContent> contentList =
				fileMapper.selectContentBySignatureCode(Lists.newArrayList(signatureCodes));
		return new StreamingResponseBody() {
			@Override
			public void writeTo(OutputStream outputStream) throws IOException {
				outputStream.write(contentList.get(0).getContent());
			}
		};
	}


	//	public Optional<SimpleEntry<String, Integer>> uploadFile(MultipartFile file) throws IOException {
//		byte[] content;
//		String fileSignature;
//		Optional<BlogFile> existFile;
//		SimpleEntry<String, Integer> entry; 
//		
//		if(file == null) 
//			throw ExceptionConstant.fileIsNotExist.get();
//		
//		content = file.getBytes();
//		fileSignature = EncodeUtil.signatureCode(content);
//		existFile = Optional.ofNullable(fileMapper.selectBySignatureCode(fileSignature));
//		
//		
//		if(existFile.isPresent()) {
//			existFile.filter(temp -> temp.getStatus().equals((byte)1)).orElseThrow(ExceptionConstant.fileIsNotlegal);
//			entry = new SimpleEntry<String, Integer>(file.getName(), existFile.map(BlogFile::getId).get());
//		}
//		else {
//			BlogFile newFile = BlogFile.builder()
//					.signatureCode(fileSignature)
//					.content(content)
//					.type(file.getContentType())
//					.size((int)file.getSize())
//					.status((byte)1)
//					.build();
//	
//			fileMapper.insertSelective(newFile);
//			fileMapper.insertContent(newFile);
//				//TODO:Exception
//			entry = new SimpleEntry<String, Integer>(file.getName(), newFile.getId());
//		}
//		
//		return Optional.ofNullable(entry);
//	}
}
